﻿using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Collections.ObjectModel;
using System.Collections.Generic;


namespace EmbeddedLanguage.SubProcessors
{
    public class AssignJSProcessor : ExpressionToJSProcessor
    {
        private bool EnteredVisitMethodOrDelegateCall;

        protected override Expression VisitMethodOrDelegateCall(Expression node, Expression node_Object, 
            MemberInfo node_Method, ReadOnlyCollection<Expression> node_Arguments, bool FromInvocation)
        {
            var callExpression = node as MethodCallExpression;
            var zerothArg = callExpression.Arguments[0] as System.Linq.Expressions.ParameterExpression;
            this.KeyVariableName = zerothArg.Name;
            if (EnteredVisitMethodOrDelegateCall)
            {
                return base.VisitMethodOrDelegateCall(node, node_Object, node_Method, node_Arguments, FromInvocation);
            }
            else
            {
                var ns = new NestedString
                {
                    Parent = this.CurrentNestedString,
                    LHS_Template = "{LHS}",
                    Waist = " = ",
                    RHS_Template = "{RHS};",
                    Comment = "AssignJSProcessor",
                    ChildSubstitutions = new Dictionary<string, int>
                    {
                        {"{LHS}", 1},
                        {"{RHS}", 2},
                    },
                    IsKaboose = true,
                    TrainOfMethodsParameter = this.KeyVariableName,
                    IgnoredChildren = new List<int>
                    {
                        0
                    }

                };
                //bba ns.Parent.ForceLineBreakOnEachChild = true;
                //ns.Parent.ChildrenContinueOnLine = false;
                bool removed = this.RemoveReturnFromParent(ns);
                if (removed)
                {
                    ns.ForceLineBreakOnLHS = true;
                    ns.Footer = "return " + this.KeyVariableName + ";";
                }
                ns.Parent.ForceLineBreakOnEachChild = true;
                this.AddArgsToNestedString(ns, node_Arguments);
            }
            return node;
        }
    }
}
